
const { ipcRenderer } = require('electron');
ipcRenderer.setMaxListeners(0);

var project = ipcRenderer.sendSync('project');
var version = JSON.parse(ipcRenderer.sendSync('read_file', project + 'version.json'));

var desktopLoader = function (path, name, callback) {
    var url = Halo.ResourceManager.getUrl(path, name);
    var ver = version[path] ? version[path][name] : null;
    var size = ver ? ver.size : 0;

    var type = (path === 'cfg' || path === 'js' || path === '') ? 'read_file' : 'read_binary';
    var data = ipcRenderer.sendSync(type, url);

    if (type === 'read_binary') {
        if (path === 'aud') {
            data = Halo.base64ToArrayBuffer(data);
        } else if (path === 'img') {
            data = 'data:img/' + name.split('.').pop().toLowerCase() + ';base64,' + data;
        } else if (path === 'vid') {
            data = 'data:video/' + name.split('.').pop().toLowerCase() + ';base64,' + data;
        } else if (Halo.ResourceManager.path3d().indexOf(path) >= 0) {
            data = Halo.base64ToUint8Array(data);
        }
    }

    if (path === 'js' && Halo.Config.bDebug) {
        var script = document.createElement('script');
        script.type = "text/javascript";
        script.src = url;
        script.onload = function () {
            document.head.removeChild(script);
            callback && callback(script);
            Halo.onLoadData && Halo.onLoadData(path, name, size);
        }
        document.head.appendChild(script);
    } else {
        callback && callback(data);
        Halo.onLoadData && Halo.onLoadData(path, name, size);
    }
};

var getAllRes = function () {
    var list = [];
    var pathes = ['cfg', 'img', 'aud', 'vid', 'geo', 'ani', 'js', 'mat', 'mdl', 'scn'];
    for (var i = 0; i !== pathes.length; ++i) {
        var path = pathes[i];
        var files = JSON.parse(ipcRenderer.sendSync('list-files', path));
        for (var j = 0; j !== files.length; ++j) {
            var name = files[j];
            if (name.startsWith('.', 0)) {
                continue;
            }
            if (Halo.ResourceManager.path3d().indexOf(path) >= 0) {
                var suffix = name.split('.').pop();
                name = name.substring(0, name.length - suffix.length - 1);
            }
            list.push({ path: path, name: name });
        }
    }
    return list;
}